package com.rongji.cms.tools.websocket.controller; /**
 * @author yang
 * @date 2023/2/6 9:49
 * @description
 */


import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.SocketIONamespace;
import com.corundumstudio.socketio.SocketIOServer;
import com.rongji.cms.tools.websocket.domain.ChatMessage;
import com.rongji.cms.tools.websocket.domain.WsMessage;
import com.rongji.cms.tools.websocket.util.SocketUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/**
 * @author yang
 * @create 2023/2/6
**/
@RestController
public class WsTestController {
    public final static String SEND_TYPE_ALL = "ALL";
    public final static String SEND_TYPE_ALONE = "ALONE";
    @Autowired
    SocketUtil socketUtil;

    @Autowired
    private SocketIOServer socketIoServer;

    @PostMapping("/testSendMsg")
    public String testSendMsg(@RequestBody WsMessage myMessage){
        Map<String, Object> map = new HashMap<>();
        map.put("msg",myMessage.getContent());

        //群发
        if (SEND_TYPE_ALL.equals(myMessage.getType())){
            socketUtil.sendToAll( map,myMessage.getChannel());
            return "success";
        }
        //指定单人
        if (SEND_TYPE_ALONE.equals(myMessage.getType())){
            socketUtil.sendToOne(myMessage.getReceiver(), map, myMessage.getChannel());
            return "success";
        }

        return "fail";
    }


    @PostMapping("/pushMsg")
    public String pushMsgByService(@RequestBody ChatMessage chatMessage) {
        SocketIONamespace namespace = socketIoServer.getNamespace(chatMessage.getNameSpace());
        Collection<SocketIOClient> allClients = namespace.getAllClients();
        for (SocketIOClient client : allClients) {
            client.sendEvent(chatMessage.getEventName(), chatMessage.getMessage());
        }
        return "success";
    }

}
